import { message } from "antd";

function createUnique() {
    const buf = new Uint32Array(1);
    crypto.getRandomValues(buf);
    return buf[0];
}

export class ProgDialog {

    readonly key: number = createUnique();

    prog(msg: string, duration: number = 0) {
        message.loading({
            content: msg,
            type: 'loading',
            key: this.key,
            duration
        });
    }

    success(msg: string, duration: number = 2) {
        message.success({
            content: `${msg} 成功`,
            type: 'success',
            key: this.key,
            duration,
            onClick: () => {
                message.destroy(this.key);
            }
        });
    }

    error(msg: string, duration: number = 0) {
        message.error({
            content: `${msg} 失败`,
            type: 'error',
            key: this.key,
            duration,
            onClick: () => {
                message.destroy(this.key);
            }
        });
    }
}

export async function runProg<T>(msg: string, cb: (d: ProgDialog) => Promise<T> ) {
    let dialog = new ProgDialog();
    dialog.prog(msg);
    try {
        await cb(dialog);     
        dialog.success(msg);
    } catch (e) {
        dialog.error(`${e} ${msg}`);
    }

}
